<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of adm
 *
 * @author Dmitry
 */
class Models_Adm extends Access_Db {
  
  public function genCode($length=6) 
  {
      $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
      $code = "";
      $clen = strlen($chars) - 1;  
      while (strlen($code) < $length) 
      {
          $code .= $chars[mt_rand(0,$clen)];  
      }
      return $code;
  } 
   
  public function isUserSet($login, $password)
  {
    $select = array(
        'id',
        'name',
        'login',
        'hash',
        'md5password',
        'email'
    );
    $md5password = md5(md5($password));
    $this->select($select, 'users',"login='$login' and md5password='$md5password'");
    $user = $this->getSelected();
    
    if(count($user) < 5)
    {
      echo 'false user<5';
      return false;
    }
    else
    {
      $this->login($md5password, $user);
      return true;
    }
  }

  public function login($md5password, $user)
  {
    if($md5password === $user['md5password'])
    {
      $hash = md5($this->genCode());
      $this->update('users', 'hash=\'' . $hash . '\'', ' id=\'' . $user['id'] . '\'');
      session_start();
      $_SESSION['id'] = $user['id'];
      $_SESSION['name'] = $user['name'];
      $_SESSION['hash'] = $hash;
    }
    else
    {
      die ("Сталася помилка!");
    }
  }
  
  public function isAuth()
  {
    if (isset ($_SESSION['hash']) and isset ($_SESSION['id']))
    {
      $select = array(
          'id',
          'hash'
      );
      $this->select($select, 'users', 'id=\'' . $_SESSION['id'] . '\'');
      $user = $this->getSelected();
      if($user['hash'] !== $_SESSION['hash'])
      {
        $this->out();
        return false;
      }
      else
      {
        return true;
      }
    }
    return false;;
  }
  
  public function out()
  {
    session_destroy();
  }
  
  public function showAdmButtons()
  {
    echo '<div class="">
            <h6>Wellcome, ' . $_SESSION['name'] .
            '! Click <a href="/' . $this->printPath() .
            'adm/logout">Out</a> for exit. Go to <a href="/' . $this->printPath() .
            'adm/menu">menu</a>.</h6>
          </div>';
  }


  public function showAllArticles()
  {
    $select = array(
        'id',
        'name',
        'content',
        'created',
        'modified',
        'menu_id'
    );
    $this->select($select, 'articles');
    $articles = array();
    while ($row = $this->getSelected())
    {
      $articles[] = $row;
    }
    return $articles;
  }
  
  public function addNewArticle()
  {
    //todo
  }
}